<template>
  <div>
    <el-tree
      ref="refTree"
      node-key="id"
      :show-checkbox="true"
      default-expand-all
      :check-strictly="true"
      :data="list"
      :props="{ label: 'name' }"
    />

    <el-button @click="hClose">取 消</el-button>
    <el-button type="primary" @click="hSubmit">确 定</el-button>
  </div>
</template>

<script>
import { tranListToTreeData } from '@/utils/index.js'
import { getPermissionList } from '@/api/permission'
import { getRoleDetail, assignPerm } from '@/api/settings'
export default {
  props: {
    roleId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      list: []
    }
  },
  created() {
    // 调用接口，获取所有的权限点数据
    this.loadPermissionList()
    // 调用接口，获取当前这个角色已经具备的权限
    this.loadPermissionByRoleId()
  },

  methods: {
    hClose() {
      // 通过父组件去关闭弹层
      this.$emit('close')
      // 清空当前的选择
      this.$refs.refTree.setCheckedKeys([])
    },
    async hSubmit() {
      // 1. 获取当前用户的选择 ----> 调用api
      try {
        const permIds = this.$refs.refTree.getCheckedKeys()
        await assignPerm({ id: this.roleId, permIds })
        console.log(permIds)
        // 提示
        this.$message.success('保存角色的权限成功')
        // 关闭弹层
        this.$emit('close')
      } catch (err) {
        console.log()
      }
    },
    async loadPermissionByRoleId() {
      try {
        // 根据roleId获取当前这个角色已经具备的权限
        const res = await getRoleDetail(this.roleId)
        console.log('当前角色的权限：', res)

        // 设置当前选中的节点
        this.$refs.refTree.setCheckedKeys(res.data.permIds)
      } catch (err) {
        console.log('错误', err)
      }
    },
    async loadPermissionList() {
      try {
        const res = await getPermissionList()
        console.log('权限点', res)
        // 保存数据
        // 数组数据转成tree
        this.list = tranListToTreeData(res.data)
      } catch (err) {
        console.log('错误', err)
      }
    }
  }
}
</script>
